package com.tim.app.ui.view;

import android.content.Context;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.util.TimeUtil;
import com.application.library.widget.roundimg.RoundedImageView;
import com.google.gson.Gson;
import com.tim.app.R;
import com.tim.app.constant.AppKey;
import com.tim.app.server.api.API_User;
import com.tim.app.server.entry.ActionStateMsg;
import com.tim.app.server.entry.Answer;
import com.tim.app.server.entry.Problem;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.FollowResult;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.ui.activity.selected.QuestionAndAnswerDetailActivity;
import com.tim.app.ui.activity.selected.AnswerActivity;
import com.tim.app.ui.activity.some_homepage.SomeoneHomepageActivity;
import com.tim.app.util.BitmapLoader;
import com.tim.app.util.ToastUtil;
import com.tim.app.util.ViewGT;

/**
 * 回答详情的header
 */

public class AnswerHeadView extends RelativeLayout implements View.OnClickListener, LSWebView.OnOpenUrlListener {

    public static final String TAG = "AnswerHeadView";

    private LSWebView wbContent;

    private TextView tvAnswerTitle;
    private TextView tvFollow;

    private RoundedImageView rivAvatar;
    private TextView tvUserName;
    private TextView tvContextTime;

    private TextView tvAnswerQuestion;
    private TextView tvAnswerCount;
    private TextView tvAgreeNumber;
    private TextView tvOppositionNumber;

    private Answer answer;

    private View rlActionContainer;
    private View icCommentContainer;

    public AnswerHeadView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        wbContent = (LSWebView) findViewById(R.id.wbContent);
        tvAnswerTitle = (TextView) findViewById(R.id.tvAnswerTitle);
        tvFollow = (TextView) findViewById(R.id.tvFollow);
        rivAvatar = (RoundedImageView) findViewById(R.id.rivAvatar);
        tvUserName = (TextView) findViewById(R.id.tvUserName);
        tvContextTime = (TextView) findViewById(R.id.tvContextTime);

        tvAnswerQuestion = (TextView) findViewById(R.id.tvAnswerQuestion);
        tvAnswerCount = (TextView) findViewById(R.id.tvAnswerCount);
        tvAgreeNumber = (TextView) findViewById(R.id.tvAgreeNumber);
        tvOppositionNumber = (TextView) findViewById(R.id.tvOppositionNumber);
        rlActionContainer = findViewById(R.id.rlActionContainer);
        icCommentContainer = findViewById(R.id.icCommentContainer);

        wbContent.setInterceptBack(false);
        wbContent.setOnOpenUrlListener(this);

        tvFollow.setOnClickListener(this);
        rivAvatar.setOnClickListener(this);
        tvUserName.setOnClickListener(this);
        tvAnswerCount.setOnClickListener(this);
        tvAnswerQuestion.setOnClickListener(this);
        tvAnswerTitle.setOnClickListener(this);

    }

    /**
     * 刷新页面
     *
     * @param data
     */
    public void setData(final Answer data) {
        if (null == data)
            return;
        answer = data;

        if (null != data.getUserMsg()) {
            if (!TextUtils.isEmpty(data.getUserMsg().getImage())) {
                BitmapLoader.ins().loadImage(data.getUserMsg().getImage(), rivAvatar);
            }
            if (!TextUtils.isEmpty(data.getUserMsg().getName())) {
                tvUserName.setText(data.getUserMsg().getName());
            }
            if (UserManager.ins().isLogin()) {
                if (UserManager.ins().getUserId().equals(answer.getUserMsg().getUserId())) {
                    tvFollow.setVisibility(View.GONE);
                }
            }
            if (TextUtils.isEmpty(answer.getUserMsg().getUserId())) {
                tvFollow.setVisibility(View.GONE);
            }
        }
        if (null != data.getActionStateMsg()) {
            if (null != data.getActionStateMsg().getUserState()) {
                tvFollow.setSelected(true);
                tvFollow.setText(R.string.hasFollow);
            } else {
                tvFollow.setSelected(false);
                tvFollow.setText(R.string.unFollow);
            }
        }
        tvContextTime.setText(getContext().getString(R.string.createTime, TimeUtil.formatTimeRuleTwo(getContext(), data.getCreateTime())));
        tvAgreeNumber.setText(getContext().getString(R.string.answerPriseNumber, String.valueOf(answer.getAgreeCount())));
        tvOppositionNumber.setText(getContext().getString(R.string.answerOppositionNumber, String.valueOf(answer.getOpposeCount())));
        if (!TextUtils.isEmpty(data.getProblemTitle())) {
            tvAnswerTitle.setText(String.valueOf(data.getProblemTitle()));
        }
        tvAnswerCount.setText(getContext().getString(R.string.answer, String.valueOf(answer.getProblemAnswerCount())));
    }

    public void showContent(String url) {
        wbContent.clearHistory();
        wbContent.openUrl(url);
    }

    @Override
    public void onOpenUrl(String url) {

    }

    @Override
    public void showLoadingLayout() {

    }

    @Override
    public void hideLoadingLayout() {
        rlActionContainer.setVisibility(View.VISIBLE);
        icCommentContainer.setVisibility(View.VISIBLE);
    }

    @Override
    public void onReceivedError() {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tvFollow:
                if (!UserManager.ins().isLogin()) {
                    ViewGT.gotoLoginActivity(getContext());
                    return;
                }
                followOrCancelFollow();
                break;
            case R.id.tvUserName:
            case R.id.rivAvatar:
                SomeoneHomepageActivity.start(getContext(), answer.getUserMsg(), false);
                break;
            case R.id.tvAnswerQuestion:
                Intent intentAnswer = new Intent(getContext(), AnswerActivity.class);
                intentAnswer.putExtra(AppKey.IS_ANSWER, true);
                intentAnswer.putExtra(AppKey.QUESTION_ID, answer.getProblemId());
                getContext().startActivity(intentAnswer);
                break;
            case R.id.tvAnswerTitle:
            case R.id.tvAnswerCount:
                Problem problem = new Problem();
                problem.setId(answer.getProblemId());
                QuestionAndAnswerDetailActivity.start(getContext(), problem, false);
                break;
        }
    }

    /**
     * 关注/取消关注
     */
    private void followOrCancelFollow() {
        tvFollow.setEnabled(false);
        if (null != answer.getActionStateMsg() && answer.getActionStateMsg().getUserState() != null) {
            int id = answer.getActionStateMsg().getUserState();
            API_User.ins().cancelFollow(TAG, id, UserManager.ins().getUserId(), answer.getUserMsg().getUserId(), AppKey.TYPE_USER, new StringResponseCallback() {
                @Override
                public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                    tvFollow.setEnabled(true);
                    if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                        tvFollow.setSelected(false);
                        tvFollow.setText(R.string.unFollow);
                        answer.getActionStateMsg().setUserState(null);
                    } else {
                        ToastUtil.showToast(errMsg);
                    }
                    return false;
                }
            });
        } else {
            API_User.ins().addFollow(TAG, UserManager.ins().getUserId(), answer.getUserMsg().getUserId(), AppKey.TYPE_USER, new StringResponseCallback() {
                @Override
                public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean formCache) {
                    tvFollow.setEnabled(true);
                    if (errCode == ResponseResult.ResultStatus.OK && resultValue != null) {
                        FollowResult result = new Gson().fromJson(resultValue, FollowResult.class);
                        if (null != result && null != result.getRes()) {
                            if (answer.getActionStateMsg() == null) {
                                answer.setActionStateMsg(new ActionStateMsg());
                            }
                            answer.getActionStateMsg().setUserState(result.getRes().getConcern().getId());
                            tvFollow.setSelected(true);
                            tvFollow.setText(R.string.hasFollow);
                        }
                    } else if (ResponseResult.ResultStatus.BE_ADD_BLACK == errCode) {
                        if (answer.getUserMsg().getSex() == AppKey.SEX_MAN) {
                            ToastUtil.showToast("由于对方的设置，你不能关注他");
                        } else {
                            ToastUtil.showToast("由于对方的设置，你不能关注她");
                        }
                    } else {
                        ToastUtil.showToast(errMsg);
                    }
                    return false;
                }
            });
        }
    }

}
